/*
 * Copyright 2014 by État de Genève (Switzerland)
 * All rights reserved.
 *
 * Author: ELCA Informatique SA
 */
define(['plugins/lifecycle'], function (lifecycle) {

    return {
        reinitPopovers: popovers,
        relayout: relayout,
        needsRelayout: registerRelayout,
        hasPopovers: registerPopovers
    };

    function popovers() {
        $('[data-toggle="popover"]').popover();
    }

    function registerPopovers() {
        lifecycle.registerFinalProcess('popover', popovers);
    }

    function registerRelayout() {
        lifecycle.registerFinalProcess('relayout', relayout);
    }

    function relayout() {

        var h = $('#cms-shell').height();
        $('.cms-sidebar').height(h);

        $('[data-height-exclude]:visible').each(function () {
            h = h - $(this).height();
        });

        // set initial height of main containers (columns)
        $('[data-height-container]').height(h);

        // correct heights depending on offsets, if offsets there is
        $('[data-height-offset]').each(function () {
            $(this).height(h - $(this).attr('data-height-offset'));
        });

        // compute height of 'relative' elements depending on relatives and containers
        $('[data-height-relative]').each(function () {
            var grp = $(this).attr('data-height-relative');
            var $container = $('[data-height-container="' + grp + '"]');
            var initialH = $container.height() - ($(this).attr('data-height-offset') || 0);

            var newH = _.reduce(
                $('[data-height-grp="' + grp + '"]').map(function () {
                    return $(this).outerHeight(true);
                }).get(),
                function (memo, val) {
                    return memo - val;
                },
                initialH
            );

            $(this).height(newH);
        });

        $('.nano').nanoScroller();
    }
});